package com.qyhl.shop.shop.settled;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.just.library.WebDefaultSettingsManager;
import com.just.library.WebSettings;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_SETTLED)
public class ShopSettledActivity extends BaseActivity {
    @BindView(R2.id.web_layout)
    LinearLayout webLayout;

    @Autowired(name = "url")
    String mUrl;

    private AgentWeb mAgentWeb;

    private WebView mWebView;

    public static final int FILECHOOSER_RESULTCODE_5 = 12;
    public static final int FILECHOOSER_RESULTCODE = 13;
    public WebChromeClient.FileChooserParams mfileChooserParams;
    public ValueCallback<Uri[]> umUploadMessages;
    public ValueCallback<Uri> mUploadMessage;

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_settled;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.fullScreen(true).statusBarDarkFont(false).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        WebViewClient mWebViewClient = new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.cancel();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        };

        WebChromeClient webChromeClient = new WebChromeClient() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                umUploadMessages = filePathCallback;
                mfileChooserParams = fileChooserParams;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String[] acceptTypes = mfileChooserParams.getAcceptTypes();
                if (acceptTypes[0].equals("video/*")) {
                    i.setType("video/*");
                } else if (acceptTypes[0].equals("image/*")) {
                    i.setType("image/*");
                }
                startActivityForResult(Intent.createChooser(i, "选择相册"), FILECHOOSER_RESULTCODE_5);
                return true;
            }

            // For Android > 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                if (acceptType.equals("video/*")) {
                    i.setType("video/*");
                } else if (acceptType.equals("image/*")) {
                    i.setType("image/*");
                }
                startActivityForResult(Intent.createChooser(i, "选择相册"),
                        FILECHOOSER_RESULTCODE);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, false);
            }
        };

        mAgentWeb = AgentWeb.with(this)//传入Activity
                .setAgentWebParent(webLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条
                .defaultProgressBarColor() // 使用默认进度条颜色
                .setWebSettings(new CustomSettings())
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(webChromeClient)
                .setReceivedTitleCallback(new ChromeClientCallbackManager.ReceivedTitleCallback() {
                    @Override
                    public void onReceivedTitle(WebView view, String title) {

                    }
                })//设置 Web 页面的 title 回调
                .createAgentWeb()//
                .ready()
                .go(mUrl);

        mWebView = mAgentWeb.getWebCreator().get();
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onResume() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//监听返回键，如果可以后退就后退
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, keyEvent);

    }

    @Override
    protected void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
        super.onDestroy();
    }

    class CustomSettings extends WebDefaultSettingsManager {
        protected CustomSettings() {
            super();
        }

        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public WebSettings toSetting(WebView webView) {
            super.toSetting(webView);
            String path = Environment.getExternalStorageDirectory().getPath() + "/baidudata";//百度地图调用需要
            File tmpFile = new File(path);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            getWebSettings().setGeolocationDatabasePath(path);
            getWebSettings().setGeolocationEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWebSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            getWebSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            getWebSettings().setJavaScriptEnabled(true);
            getWebSettings().setDomStorageEnabled(true);
            getWebSettings().setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
            getWebSettings().setAllowFileAccess(false); //允许加载本地文件html  file协议, 这可能会造成不安全 , 建议重写关闭
            getWebSettings().setAllowFileAccessFromFileURLs(false); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
            getWebSettings().setAllowUniversalAccessFromFileURLs(false);//允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源
            getWebSettings().setUseWideViewPort(true);
            getWebSettings().setUserAgentString("Android");
            getWebSettings().setSupportZoom(true);
            getWebSettings().setBuiltInZoomControls(true);
            return this;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            if (null == data) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            } else {
                Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE_5) {// 5.0适配，主要是因为5.0的返回参数不同。
            // 处理5.0的callback
            if (umUploadMessages != null) {
                if (null != data) { // 5.0的处理方式不同，要注意。
                    ArrayList<String> resultList = data.getStringArrayListExtra("data");
                    umUploadMessages.onReceiveValue(mfileChooserParams.parseResult(resultCode, data));
                    umUploadMessages = null;
                } else {
                    umUploadMessages.onReceiveValue(null);
                }
            }
        }
    }

    @OnClick({R2.id.back_btn, R2.id.close_btn})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
            }
        } else if (viewId == R.id.close_btn) {
            finish();
        }
    }
}
